#include "../stdafx.h"
#include "SkypeAPI-Carbon.h"
#include "MagicScannerClient.h"

#define TIMER_INTERVAL 5 * 60
#define API_KEY "AQIAAHMCNhqzArCrVryNriBJraQyVJzP"
#define REFERRER "Mac.SkypePlugin"

static SkypeDelegate s_skypeDelegate;
static EventLoopTimerRef s_timerRef;
static EventLoopTimerUPP s_timerProc;
static CMagicScannerClient s_cnt;

static void
SkypeBecameAvailable(CFPropertyListRef aNotification)
{
	if (s_timerRef == NULL)
	{
		InstallEventLoopTimer(GetMainEventLoop(),  0,  kEventDurationSecond * TIMER_INTERVAL,  s_timerProc, NULL, &s_timerRef);
	}
}

static void
SkypeBecameUnavailable(CFPropertyListRef aNotification)
{
	if (s_timerRef != NULL)
	{
		RemoveEventLoopTimer(s_timerRef);
		s_timerRef = NULL;
	}
}

#ifdef TRACE_SKYPE
static void
SkypeNotificationReceived(CFStringRef strNotification)
{
	if (strNotification == NULL)
		return;
	
	char azBuffer[128];
	if (CFStringGetCString(strNotification, azBuffer, ARRAYSIZE(azBuffer), kCFStringEncodingUTF8))
		printf("%s\n", azBuffer);
}
#endif

static void
SkypeAttachResponse(unsigned int aAttachResponseCode)
{
	if (aAttachResponseCode != 1)
		return;

	// SkypeBecameAvailable may be missing at this time.
	//
	SkypeBecameAvailable(NULL);
}

static void
InitSkype()
{
#ifdef TRACE_SKYPE
	s_skypeDelegate.SkypeNotificationReceived = SkypeNotificationReceived;
#else
	s_skypeDelegate.SkypeNotificationReceived = NULL;
#endif
	s_skypeDelegate.SkypeAttachResponse       = SkypeAttachResponse;
	s_skypeDelegate.SkypeBecameAvailable      = SkypeBecameAvailable;
	s_skypeDelegate.SkypeBecameUnavailable    = SkypeBecameUnavailable;
	s_skypeDelegate.clientApplicationName     = CFSTR("Wi2Geo.SkypePlugin");
	SetSkypeDelegate(&s_skypeDelegate);
}

static pascal void
TimerCallback(EventLoopTimerRef timer, void* pUserArg)
{
	std::string strCmd("SET PROFILE RICH_MOOD_TEXT ");
	strCmd += s_cnt.GetLocationHtml(API_KEY, REFERRER);
	CFStringRef strCmdRef = CFStringCreateWithCString(NULL, strCmd.c_str(), kCFStringEncodingUTF8);
//	CFStringRef strResponse = 
	SendSkypeCommand(strCmdRef);
//	if (strResponse != NULL)
//		CFRelease(strResponse);
	
	CFRelease(strCmdRef);
}

int main (int argc, char * const argv[]) 
{
	while (!IsSkypeRunning())
	{
		// Skype is not started yet.
		//
		sleep(TIMER_INTERVAL);
	}

	s_timerProc = NewEventLoopTimerUPP(TimerCallback);
	InitSkype();
	ConnectToSkype();

	RunApplicationEventLoop();
	DisposeEventLoopTimerUPP(s_timerProc);
    return 0;
}
